package com.mazaiting.mybatisplus.encrypt.provider;

import com.mazaiting.mybatisplus.encrypt.FieldEncrypt;
import com.mazaiting.mybatisplus.encrypt.IEncryptor;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 加密处理器提供者类
 *
 * @author danghailiang
 */
public class EncryptorProvider {
    /**
     * 注解为Key，加密器对象为value
     */
    private static final ConcurrentHashMap<FieldEncrypt, IEncryptor> CACHE = new ConcurrentHashMap<>();

    /**
     * 通过注解获取加密器对象
     * @param fieldEncrypt 加密注解
     * @param globalDefaultEncryptor 加密器对象
     * @return  返回加密器
     */
    public static IEncryptor get(FieldEncrypt fieldEncrypt, Class<? extends IEncryptor> globalDefaultEncryptor) {
        // globalDefaultEncryptor is always the same object
        // 查找加密器并返回啊
        return CACHE.computeIfAbsent(fieldEncrypt, ignored -> {
            try {
                // 获取加密器clazz
                Class<? extends IEncryptor> specifiedEncryptor = fieldEncrypt.encryptor();
                // 判断specifiedEncryptor 是IEncryptor的实现类，不是则返回它本身
                Class<? extends IEncryptor> encryptor = specifiedEncryptor == IEncryptor.class ? globalDefaultEncryptor : specifiedEncryptor;
                // 返回加密器构造对象clazz.getDeclaredConstructor().newInstance()
                return encryptor.getDeclaredConstructor().newInstance();
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
    }
}
